package com.cskaoyan.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.reverseengineering.MarketStorage;
import com.cskaoyan.bean.reverseengineering.MarketStorageExample;
import com.cskaoyan.bean.vo.StorageListVO;
import com.cskaoyan.config.AliyunComponent;
import com.cskaoyan.mapper.MarketStorageMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 创建日期: 2022/05/05 21:58
 *
 * @author yangfan
 */
@Service
public class StorageServiceImpl implements StorageService {

    @Value("${spring.resources.static-locations}")
    private String domain;

    @Autowired
    MarketStorageMapper marketStorageMapper;

    @Autowired
    AliyunComponent aliyunComponent;

    @Override
    public MarketStorage insert(MultipartFile multipartFile, HttpServletRequest request){

        MarketStorage marketStorage = new MarketStorage();

        // 文件名
        marketStorage.setName(multipartFile.getOriginalFilename());


        // 文件key --->  随机生成UID
        String uuid = UUID.randomUUID().toString();
        // 得到后缀 .jpg
        int index = multipartFile.getOriginalFilename().indexOf(".");
        String substring = multipartFile.getOriginalFilename().substring(index);


        //TODO
        // 文件大小
        marketStorage.setSize((int) multipartFile.getSize());

        // type
        marketStorage.setType(multipartFile.getContentType());

        // // url
        // StringBuffer requestURL = request.getRequestURL();
        // int index1 = requestURL.indexOf("/admin");
        // String url = requestURL.substring(0, index1);
        // marketStorage.setKey(uuid + substring);
        // marketStorage.setUrl(url + "/wx/storage/fetch/" + uuid + substring);

        // 使用aliyun Oss存储照片
        // String accessKeyId = "LTAI5tL96xp1xVrcHgJoMj6E";
        // String accessKeySecret ="FMoV4fo8BIU4o1plVyh0w0YwOa5k05";
        // String endPoint = "oss-cn-hangzhou.aliyuncs.com";
        // String bucket = "pics-bed-lxc";

        String fileName = uuid + substring;
        System.out.println(fileName);
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        // try {
        //     InputStream inputStream = multipartFile.getInputStream();
        //     PutObjectResult putObjectResult = ossClient.putObject(bucket, fileName, inputStream);
        // } catch (IOException e) {
        //     e.printStackTrace();
        // }

        aliyunComponent.fileUpload(fileName,inputStream);

        // url
        marketStorage.setKey(uuid + substring);
        marketStorage.setUrl("https://" + aliyunComponent.getOss().getBucket() + "." + aliyunComponent.getOss().getEndPoint() + "/" + uuid + substring);



        // // 存储文件
        // try {
        //     int index2 = domain.indexOf(":");
        //     String substring1 = domain.substring(index2 + 1);
        //     multipartFile.transferTo(new File(substring1,
        //             uuid + substring));
        // } catch (IOException e) {
        //     e.printStackTrace();
        // }

        // addTime 和 updateTime
        Date date = new Date();
        marketStorage.setAddTime(date);
        marketStorage.setUpdateTime(date);



        marketStorageMapper.insert(marketStorage);


        return marketStorage;
    }


    /**
     * 系统管理，对象存储，列表显示
     * @param name
     * @param key
     * @param param
     * @return
     */
    @Override
    public StorageListVO query(String name, String key, BaseParam param) {

        Integer page = param.getPage();//页码
        Integer limit = param.getLimit();//数据量
        String sort = param.getSort();//排序列
        String order = param.getOrder();//desc\asc
        // 分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, limit);
        //执行查询过程中拼接分页信息
        MarketStorageExample marketStorageExample = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = marketStorageExample.createCriteria();

        marketStorageExample.setOrderByClause(sort+" "+order);
        if (name != null && !"".equals(name)){
            criteria.andNameLike("%" + name + "%");
        }
        if ( key != null && !"".equals(key)){
            criteria.andKeyEqualTo(key);
        }
        criteria.andDeletedEqualTo(false);
        List<MarketStorage> marketStorages = marketStorageMapper.selectByExample(marketStorageExample);

        //total、pages、list
        //通过PageHelper帮我们来获得一些和分页相关的信息PageInfo
        //使用其有参构造方法 → 形参写来源于数据库的list
        PageInfo<MarketStorage> pageInfo = new PageInfo<>(marketStorages);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return StorageListVO.data(total,pages,limit,page,marketStorages);
    }

    /**
     * 系统管理，对象存储，删除对象
     * @param marketStorage
     * @return
     */
    @Override
    public int storageDelete(MarketStorage marketStorage) {

        marketStorage.setUpdateTime(new Date());
        marketStorage.setDeleted(true);
        int affectedRows = marketStorageMapper.updateByPrimaryKeySelective(marketStorage);
        return affectedRows;
    }

    @Override
    public int storageUpdate(MarketStorage marketStorage) {

        marketStorage.setAddTime(null);
        marketStorage.setUpdateTime(new Date());

        int affectedRows = marketStorageMapper.updateByPrimaryKeySelective(marketStorage);

        return affectedRows;
    }
}
